Page({
 data: {
  // 类别数据
  allProducts: [],
  // 控制 loading 显示隐藏
  loading: true,
  // 搜索
  search: '',
  // 布局
  vertical: ''
 },
 // 静态数据
 static: {
  page: 1
 },
 // 获取类别列表
 getTopCategoryCode() {
  wx.request({
   url: 'https://starmid.minutestars.com/api/product4color/getPageProducts4All',
   data: {
    "pageIndex": this.static.page,
    "pageSize": 8,
    "tableView": "AllProductsView4Color",
    "searchWord": '',
    "inDays": ''
   },
   success: (res) => {
    let { Result, Data } = res.data
    if (Result.Success) {
     Data.products.forEach((item, index) => {
      if (item.promoteDiscount) {
       item.promoteDiscount = Math.fround(item.price * item.promoteDiscount).toFixed(2)
      }
     })
     // 将请求到的数据给响应式数据
     this.setData({
      allProducts: [...this.data.allProducts, ...Data.products]
     })
     // 隐藏 loading
     this.setData({
      loading: this.data.loading = true
     })
     // 数据请求完毕关闭loading
     wx.hideLoading()
    }
   }
  })
 },
 // 发起搜索请求 
 getSearch() {
  wx.request({
   url: 'https://starmid.minutestars.com/api/product4color/getPageProducts4All',
   data: {
    pageIndex: this.static.page,
    pageSize: 8,
    tableView: 'AllProductsView4Color',
    searchWord: this.data.search,
    inDays: ''
   },
   success: (res) => {
    let { Data, Result } = res.data
    if (Result.Success) {
     Data.products.forEach((item, index) => {
      if (item.promoteDiscount) {
       item.promoteDiscount = Math.fround(item.price * item.promoteDiscount).toFixed(2)
      }
     })
     // 获取到的数据
     this.setData({ allProducts: [...this.data.allProducts, ...Data.products] })
     // 关闭loading加载
     wx.hideLoading()
    }
   }
  })
 },
 // 页面加载
 onLoad() {
  wx.showLoading({
   title: '加载中...',
  })
  this.getTopCategoryCode()
 },
 // 页面上拉触底事件的处理函数
 onReachBottom() {
  this.setData({
   loading: this.data.loading = false
  })
  this.static.page++
  if (this.data.search) {
   this.getSearch()
  } else {
   this.getTopCategoryCode()
  }
 },
 // 搜索框搜索处理事件
 search(event) {
  wx.showLoading({
   title: '加载中...',
  })
  this.setData({ search: event.detail, allProducts: [], loading: true })
  if (event.detail) {
   this.getSearch()
  } else {
   this.getTopCategoryCode()
  }
 },
 // 切换布局
 toggleLayout() {
  if (this.data.vertical) {
   this.setData({ vertical: '' })
  } else {
   this.setData({ vertical: 'vertical' })
  }
 }


})